/**
 * 
 */
package com.wisdytech.linkdcs.equipment.service.impl;

import java.io.IOException;

import com.wisdytech.linkdcs.factory.model.Area;
import com.wisdytech.linkdcs.factory.model.Factory;
import com.wisdytech.linkdcs.factory.model.ProductionLine;
import com.wisdytech.linkdcs.factory.model.Shop;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.event.EquipEvent;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.enums.ActionType;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.ImportExcelUtils;
import com.wisdytech.linkdcs.account.dao.TtEqAccountDao;
import com.wisdytech.linkdcs.account.dao.TtEqEquipmentAidDao;
import com.wisdytech.linkdcs.account.model.TtEqEquipmentAid;
import com.wisdytech.linkdcs.equipment.dao.EquipPropertyDao;
import com.wisdytech.linkdcs.equipment.dao.EquipUsersDao;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionClientDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipAlarmParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
import com.wisdytech.linkdcs.equipment.dao.IEqToClientDao;
import com.wisdytech.linkdcs.equipment.model.CollectionClient;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.model.EquipAlarmParam;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.EquipProperty;
import com.wisdytech.linkdcs.equipment.model.EquipUsers;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.model.EquipmentToClient;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import com.wisdytech.linkdcs.equipment.vo.EquipPropertyVO;
import com.wisdytech.linkdcs.factory.dao.TmAreaDao;
import com.wisdytech.linkdcs.factory.dao.TmFactoryDao;
import com.wisdytech.linkdcs.factory.dao.TmProductionLineDao;
import com.wisdytech.linkdcs.factory.dao.TmShopDao;
import com.wisdytech.linkdcs.factory.service.IFactoryModelCommonService;
import com.wisdytech.linkdcs.factory.vo.FactoryModelResultVO;
import com.wisdytech.linkdcs.factory.vo.FactoryModelSearchVO;
import com.wisdytech.linkdcs.system.dao.ISysOperationDao;
import com.wisdytech.linkdcs.system.dao.ISysUserDao;
import com.wisdytech.linkdcs.system.model.SysOperation;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.ToolConfig;

/**
 * <p>
 * ClassName: 
 * </p>
 * <p>
 * Description: 
 * </p>
 * <p>
 * Author: kongming
 * </p>
 * <p>
 * Date: 2017-9-29
 * </p>
 */
@Service("equipmentRegisterService")
@Transactional
public class EquipmentRegisterServiceImpl extends BaseService<IEqEquipmentDao, Equipment> implements IEquipmentRegisteredService{
    /**
     * 注入设备dao
     */
    @Resource
    private IEqEquipmentDao equipDao;
    /**
     * 注入设备类别dao
     */
    @Resource
    private IEqModelDao modelDao;
    /**
     * 注入设备采集器Dao
     */
    @Resource
    private IEqCollectionClientDao clientDao;
    /**
     * 注入预警定义dao
     */
    @Resource
    private IEqEquipAlarmParamDao alarmParamDao;
    
    
    /**设备与终端关联表**/
    @Resource
    private IEqToClientDao etclientDao;
    
    /**处理设备注册事件推送*/
    @Autowired
    ApplicationContext applicationContext;
    
    @Resource
    private IFactoryModelCommonService factoryModelCommonService;
    @Resource
    private TtEqEquipmentAidDao ttEEquipmentAidDao;
    @Resource
    private ISysOperationDao iSysOperationDao;
    @Resource
    private TmAreaDao tmAreaDao;
    @Resource
    private TmFactoryDao tmFactoryDao;
    @Resource
    private TmProductionLineDao tmProductionLineDao;
    @Resource
    private TmShopDao tmShopDao;
    @Resource
    private ISysUserDao iSysUserDao;
    @Resource
    private EquipPropertyDao equipPropertyDao;
    @Resource
    private EquipUsersDao equipUsersDao;
    @Override
    public StandardResult addEquipment(Equipment equipment, String loginName) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        //验证设备编号的唯一性
        List<Equipment> equipList;
        equipList = equipDao.selectPage(new Page<Equipment>(1, 1), ew.eq("EQUIP_CODE", equipment.getEquipCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!equipList.isEmpty()) {
            return StandardResult.getFailResult(CommonConstants.EQUIP_CODE);
        }
        
    	if(StringUtils.isNoneBlank(equipment.getOperatingPersonnels())) {
    		EntityWrapper<EquipUsers> ew1 = new EntityWrapper<>();
    		ew1.eq("EQUIP_CODE", equipment.getEquipCode());
    		equipUsersDao.delete(ew1);
    		//添加操作人
    		String[] operatingPersonnels = equipment.getOperatingPersonnels().split(",");
    		for(String operatingPersonnel : operatingPersonnels) {
    			EquipUsers equipUsers = new EquipUsers();
    			equipUsers.setPkId(BaseUtil.getUUID());
    			equipUsers.setEquipCode(equipment.getEquipCode());
    			equipUsers.setOperatingPersonnel(operatingPersonnel);
    			equipUsers.setDelFlag(CommonConstants.DEL_FLAG);
    			equipUsers.insert();
    		}
    	}
    	//判断是否需要处理辅助类设备关联
    	if(StringUtils.isNoneBlank(equipment.getAidEquipCodes())) {
    		EntityWrapper<TtEqEquipmentAid> dew
    			=new EntityWrapper<>();
    		//删除原绑定的辅助类设备
    		dew.eq("EQUIP_CODE", equipment.getEquipCode());
    		ttEEquipmentAidDao.delete(dew);
    		
    		//添加新的辅助类设备关联
    		String[] aidEquipCodes = equipment.getAidEquipCodes().split(",");
    		for(String aidEquipCode : aidEquipCodes) {
    			TtEqEquipmentAid aid =new TtEqEquipmentAid();
    			aid.setPkId(BaseUtil.getUUID());
    			aid.setEquipCode(equipment.getEquipCode());
    			aid.setAidEquipCode(aidEquipCode);
    			ttEEquipmentAidDao.insert(aid);
    		}
    	}
    	
    	//添加附加属性
    	List<EquipProperty> propertys = equipment.getPropertys();
    	for(EquipProperty property : propertys) {
    		property.setPkId(BaseUtil.getUUID());
    		property.setEquipCode(equipment.getEquipCode());
    		equipPropertyDao.insert(property);
    	}
       equipment.setPkId(BaseUtil.getUUID());
       equipment.setDelFlag(CommonConstants.DEL_FLAG);
       equipment.setCreateUser(loginName);
       equipment.setCreateDate(new Date());
       equipment.setUpdateDate(new Date());
       equipment.setEquipSource("0");//设定数据来源
       int equipmentCount =equipDao.insert(equipment);
       if (equipmentCount<=0){
           throw new ServiceException("新增失败");
       }
       
       //推送设备新增事件
       List<String> equipIds=new ArrayList<>(); 
       equipIds.add(equipment.getPkId());
       List<String> equipCodes=new ArrayList<>(); 
       equipCodes.add(equipment.getEquipCode());
       EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.ADD);
       event.setDealUser(loginName);
       applicationContext.publishEvent(event);
       
        return StandardResult.getSuccessResult();
    }

    @Override
    public StandardResult updateEquipment(Equipment equipment, String loginName) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        //验证设备编号的唯一性--修改功能
        List<Equipment> equipList;
        equipList = equipDao.selectPage(new Page<Equipment>(1, 1),ew.eq("EQUIP_CODE", equipment.getEquipCode()).ne("pk_id", equipment.getPkId()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (equipList.size() > 0){
            return StandardResult.getFailResult(CommonConstants.EQUIP_CODE);
        }
    	if(StringUtils.isNoneBlank(equipment.getOperatingPersonnels())) {
    		EntityWrapper<EquipUsers> ew1 = new EntityWrapper<>();
    		ew1.eq("EQUIP_CODE", equipment.getEquipCode());
    		equipUsersDao.delete(ew1);
    		//添加操作人
    		String[] operatingPersonnels = equipment.getOperatingPersonnels().split(",");
    		for(String operatingPersonnel : operatingPersonnels) {
    			EquipUsers equipUsers = new EquipUsers();
    			equipUsers.setPkId(BaseUtil.getUUID());
    			equipUsers.setEquipCode(equipment.getEquipCode());
    			equipUsers.setOperatingPersonnel(operatingPersonnel);
    			equipUsers.setDelFlag(CommonConstants.DEL_FLAG);
    			equipUsers.insert();
    		}
    	}
    	//判断是否需要处理辅助类设备关联
    	if(StringUtils.isNoneBlank(equipment.getAidEquipCodes())) {
    		EntityWrapper<TtEqEquipmentAid> dew
    			=new EntityWrapper<>();
    		//删除原绑定的辅助类设备
    		dew.eq("EQUIP_CODE", equipment.getEquipCode());
    		ttEEquipmentAidDao.delete(dew);
    		
    		//添加新的辅助类设备关联
    		String[] aidEquipCodes = equipment.getAidEquipCodes().split(",");
    		for(String aidEquipCode : aidEquipCodes) {
    			TtEqEquipmentAid aid =new TtEqEquipmentAid();
    			aid.setPkId(BaseUtil.getUUID());
    			aid.setEquipCode(equipment.getEquipCode());
    			aid.setAidEquipCode(aidEquipCode);
    			ttEEquipmentAidDao.insert(aid);
    		}
    	}
    	//先删除
    	EntityWrapper<EquipProperty> ew1 = new EntityWrapper<>();
    	ew1.eq("EQUIP_CODE", equipment.getEquipCode());
    	equipPropertyDao.delete(ew1);
    	//再添加
    	List<EquipProperty> propertys = equipment.getPropertys();
    	for(EquipProperty property : propertys) {
    		property.setPkId(BaseUtil.getUUID());
    		property.setEquipCode(equipment.getEquipCode());
    		equipPropertyDao.insert(property);
    	}
    	
    	
        equipment.setUpdateDate(new Date());
        equipment.setUpdateUser(loginName);
        int count = equipDao.updateById(equipment);
        if (count<=0) {
            throw new ServiceException("修改失败");
        }
        
        //推送设备新增事件
        List<String> equipIds=new ArrayList<>(); 
        equipIds.add(equipment.getPkId());
        List<String> equipCodes=new ArrayList<>(); 
        equipCodes.add(equipment.getEquipCode());
        EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.UPDATE);
        event.setDealUser(loginName);
        applicationContext.publishEvent(event);
        return StandardResult.getSuccessResult();
    }
    @Override
    public Equipment getEquipmentRegisterById(String id) {
    	Equipment equip = equipDao.selectDetailById(id);
    	List<TtEqEquipmentAid> list = mergeAidEquipInfo(equip.getEquipCode());
    	List<EquipUsers> equipUserList =  mergeEquipUsers(equip.getEquipCode());
    	equip.setEquipmentAids(list);
    	equip.setEquipUsers(equipUserList);
        return equip;
    }

    private List<EquipUsers> mergeEquipUsers(String equipCode) {
    	List<EquipUsers> list = iSysUserDao.selectEquipUsers(equipCode);
		return list;
	}

	@Override
    public StandardResult delEquipmentById(String id,String loginName) {
        String[] ids = id.split(",");
        //设备编码列表
        List<String> equipCodes =new ArrayList<>();
        
        for (String pkId : ids) {
            //设备删除为假删除
            Equipment equipment = equipDao.selectById(pkId);
            int alarmParamCount = alarmParamDao.selectCount(new EntityWrapper<EquipAlarmParam>().eq("equip_id", pkId).eq("del_flag", CommonConstants.DEL_FLAG));
            if  (alarmParamCount > 0) {
                return StandardResult.getFailResult(CommonConstants.EQUIPMENT_ALARM);
            }
            
            //设备关联终端个数
            int eqToClientNums =
            		etclientDao.selectCount(new EntityWrapper<EquipmentToClient>().eq("EQUIP_ID", pkId));
            
            
            if (eqToClientNums>0) {
                return StandardResult.getFailResult(CommonConstants.EQUIPMENT_CONNECT);
            }
            
            
            equipment.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
            int count = equipDao.updateById(equipment);
            if (count <= 0){
                throw new ServiceException("删除失败");
            }
            
            equipCodes.add(equipment.getEquipCode());
        }
        
        //推送设备新增事件
        List<String> equipIds=Arrays.asList(ids);
        EquipEvent event =new EquipEvent(this,equipIds,equipCodes, ActionType.UPDATE);
        event.setDealUser(loginName);
        applicationContext.publishEvent(new EquipEvent(this,equipIds,equipCodes, ActionType.DEL));
        
        
        return StandardResult.getSuccessResult();
    }

    @Override
    public List<Equipment> listAllEquipment(String modelId) {
        return equipDao.listAllEquipment(modelId);
    }
    @Override
    public List<Equipment> listAllEquipmentByOperationId(String operationId, String serach) {
        EntityWrapper<Equipment> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(serach)) {
            ew.like("equip_code", serach);
        }
//        ew.eq("OPERATION_ID", operationId);
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        return equipDao.selectList(ew);
    }

    @Override
    public  Equipment getEquipmentByEquipCode(String equipCode) {
        return equipDao.getEquipmentByEquipCode(equipCode);
    }

    @Override
    public List<Equipment> selectByCilentId(String equipClientId) {
        return equipDao.selectByClientId(equipClientId);
    }

    @Override
    public PageInfo<Equipment> searchEquipmentByCode(Filter filter, String code) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        ew.like("EQUIP_CODE", code, SqlLike.DEFAULT);
        ew.orderBy("CREATE_DATE", false);
        List<Equipment> list =
                super.beforeList(IEqEquipmentDao.class, filter).selectList(ew);
        
        return new PageInfo<Equipment>(list);
    }

    @Override
    public Equipment getEquipmentByEquipId(String equipId) {
//        EntityWrapper<Equipment> ew =new EntityWrapper<>();
//        ew.eq("del_flag", CommonConstants.DEL_FLAG);
//        ew.eq("pk_id", equipId);
//        Equipment equip = new Equipment();
        return equipDao.selectById(equipId);
    }

	@Override
	public Equipment equipCodeChangeByeqCode(String equipCode) {
		if(equipCode==null || equipCode=="") {
			return new Equipment();
		}
		return equipDao.equipCodeChangeByeqCode(equipCode);
	}

	@Override
	public PageInfo<Equipment> searchEquipByType(Filter filter,String search, String type,String equipCode) {
		// TODO Auto-generated method stub
		
		//查找设备工序
		String operationId="";
		if(StringUtils.isNotBlank(equipCode)) {
			Equipment  equipment =equipDao.getEquipmentByEquipCode(equipCode);
			operationId=equipment.getOperationId();
		}
		
		
		List<Equipment> list=this.beforeList(IEqEquipmentDao.class, filter)
				.searchEquipByType(search, type,operationId);
		return new PageInfo<Equipment>(list);
	}

	@Override
	public PageInfo<Map<String, Object>> listEquipInfoByFilter(String equipCode, String equipName, String operationId,
			String supplier, Filter filter) {
		 Map<String, Object> params = new HashMap<>();
	        if(StringUtils.isNotBlank(equipCode)) {
	            params.put("equipCode",equipCode);
	        }
	        if(StringUtils.isNotBlank(equipName)) {
	            params.put("equipName",equipName);
	        }
	        if(StringUtils.isNotBlank(operationId)) {
	            params.put("operationId",operationId);
	        }
	        if(StringUtils.isNotBlank(supplier)) {
	            params.put("supplier",supplier);
	        }
	        List<Map<String,Object>> list = this.beforeList(IEqEquipmentDao.class,filter).listEquipInfoByFilter(params);
	        for (Map<String, Object> map: list) {
	            mergeEquipInfo(map);
	        }
	        PageInfo<Map<String, Object>> page = new PageInfo<>(list);
	        return page;
	}
	
    /**
     * 合并调用接口传入的设备其他信息
     */
    private List<TtEqEquipmentAid> mergeAidEquipInfo(String equipCode) {
        if(equipCode!=null) {
            //补充辅助类设备
            List<TtEqEquipmentAid>  aids =
            		ttEEquipmentAidDao.selectAids(equipCode);  
            return aids;
        }
        return null;
        
    }
    
    /**
     * 合并调用接口传入的设备其他信息
     * @param map 传入map
     */
    private void mergeEquipInfo(Map<String, Object> map) {
        if(map!=null) {
            //补充辅助类设备
            List<TtEqEquipmentAid>  aids =
            		ttEEquipmentAidDao.selectAids(map.get("equipCode").toString());
            map.put("aidEquips", aids);
            
        }

    }

	@Override
	public List<Equipment> getAidEquips(String operationId) {
        //补充辅助类设备
        List<Equipment>  eqList = equipDao.getAidEquips(operationId);
        //判断辅助类设备是否添加
        List<Equipment>  eqAid = new ArrayList<>();
        for(Equipment equipment : eqList) {
        	EntityWrapper<TtEqEquipmentAid> ew = new EntityWrapper<>();
        	ew.eq("AID_EQUIP_CODE", equipment.getEquipCode());
        	List<TtEqEquipmentAid>  aids = ttEEquipmentAidDao.selectList(ew);
        	if(aids.isEmpty()) {
        		eqAid.add(equipment);
        	}
        }
		return eqAid;
	}

	@Override
	public void delAidEquip(String equipCode, String aidEquipCode) {
		//删除已存在的辅助类设备
    	EntityWrapper<TtEqEquipmentAid> dew
				=new EntityWrapper<>();
		dew.eq("AID_EQUIP_CODE", aidEquipCode);
		ttEEquipmentAidDao.delete(dew);
		
	}

	@Override
	public Equipment getEquipInfoByCode(String equipCode) {
		Equipment equipment = new Equipment();
		equipment.setEquipCode(equipCode);
		return equipDao.selectOne(equipment);
	}

	@Override
	public void batchImportEquip(MultipartFile file, SysUser operator) {

        if (file == null) {
            throw new ServiceException("文件为空");
        }
        if (operator ==null) {
            throw new ServiceException("操作人不能为空");
        }
        int errorRow=0;
        try {
            String fileName = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            List<List<Object>> data = ImportExcelUtils.getDataListByExcel(in, fileName);
            if (data == null || data.size() == 0) {
                throw new ServiceException("表格数据为空");
            }
            //i 从1开始，去除表头数据，根据自己的模板而定
            for (int i = 1; i < data.size(); i++) {
                errorRow = i;
                Equipment equip = new Equipment();
                equip.setPkId(BaseUtil.getUUID());
                equip.setCreateDate(new Date());
                equip.setCreateUser(operator.getUsername());
                equip.setDelFlag(CommonConstants.DEL_FLAG);
                if (data.get(i).get(0) == null||StringUtils.isBlank(data.get(i).get(0).toString())) {
                    throw new ServiceException("第"+i+"行第1列设备编号数据不能为空");
                }
                if(!checkEquipCode(data.get(i).get(0).toString())) {
                    throw new ServiceException("第"+i+"行第1列设备编号已存在");
                }
                equip.setEquipCode(data.get(i).get(0).toString());
                if (data.get(i).get(1) == null||StringUtils.isBlank(data.get(i).get(1).toString())) {
                    throw new ServiceException("第"+i+"行第2列设备名称不能为空");
                }
                equip.setEquipName(data.get(i).get(1).toString());
                if (data.get(i).get(2) == null||StringUtils.isBlank(data.get(i).get(2).toString())) {
                    throw new ServiceException("第"+i+"行第3列设备型号数据不能为空");
                }
                if(!checkModelCode(data.get(i).get(2).toString())) {
                    throw new ServiceException("第"+i+"行第3列设备型号数据在数据库中不存在");
                }
                equip.setModelCode(data.get(i).get(2).toString());
                equip.setPlcProtocal(data.get(i).get(3).toString());
                if (data.get(i).get(4) == null||StringUtils.isBlank(data.get(i).get(4).toString())) {
                    throw new ServiceException("第"+i+"行第5列工序编码不能为空");
                }
                String opCode = data.get(i).get(4).toString();
                SysOperation operation = new SysOperation();
                operation.setCode(opCode);
                SysOperation op = iSysOperationDao.selectOne(operation);
                if(op!=null) {
                	equip.setOperationId(op.getPkId());
                }else {
                    throw new ServiceException("第"+i+"行第5列工序编码在数据库中不存在");
                }
                equip.setAidEquipCodes(data.get(i).get(5).toString());
                Factory Factory = new Factory();
                Factory.setFactoryCode(data.get(i).get(6).toString());
                Factory.setDelFlag(CommonConstants.DEL_FLAG);
                Factory fc = tmFactoryDao.selectOne(Factory);
                if(fc!=null) {
                	equip.setFactoryId(fc.getPkId());
                }else{
                    throw new ServiceException("第"+i+"行第7列厂区编码不存在");
                }
                ProductionLine ProductionLine = new ProductionLine();
                ProductionLine.setDelFlag(CommonConstants.DEL_FLAG);
                ProductionLine.setLineCode(data.get(i).get(7).toString());
                ProductionLine pl =  tmProductionLineDao.selectOne(ProductionLine);
                if(pl!=null) {
                	equip.setLineId(pl.getPkId());
                }else {
                    throw new ServiceException("第"+i+"行第8列产线编码不存在");
                }
                Shop Shop = new Shop();
                Shop.setShopCode(data.get(i).get(8).toString());
                Shop.setDelFlag(CommonConstants.DEL_FLAG);
                Shop sp = tmShopDao.selectOne(Shop);
                if(sp!=null) {
                	equip.setShopId(sp.getPkId());
                }else {
                    throw new ServiceException("第"+i+"行第9列车间编码不存在");
                }
                Area Area = new Area();
                Area.setAreaCode(data.get(i).get(9).toString());
                Area.setDelFlag(CommonConstants.DEL_FLAG);
                Area a = tmAreaDao.selectOne(Area);
                if(a!=null) {
                	 equip.setAreaId(a.getPkId());
                }else {
                    throw new ServiceException("第"+i+"行第10列区域编码不存在");
                }
                if (data.get(i).get(10) == null||StringUtils.isBlank(data.get(i).get(10).toString())) {
                    throw new ServiceException("第"+i+"行第11列设备类目数据不能为空");
                }
                equip.setEquipCategory(data.get(i).get(10).toString());
                equip.setoValue(data.get(i).get(11).toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
                Date utilDate = sdf.parse(data.get(i).get(12).toString());
                equip.setUseDate(utilDate);
                equip.setToFixedAssets(data.get(i).get(13).toString());
                equip.setLastCheck(data.get(i).get(14).toString());
                SysUser SysUser = new SysUser();
                SysUser.setUsername(data.get(i).get(15).toString());
                SysUser s = iSysUserDao.selectOne(SysUser);
                if(s!=null) {
                	equip.setResponsiblePerson(s.getPkId());
                }
                equip.setCostCenter(data.get(i).get(16).toString());
                equip.setDepartment(data.get(i).get(17).toString());
                equip.setEquipStatus(data.get(i).get(18).toString());
                String name = data.get(i).get(19).toString();
                this.addOperatingPersonnels(name,equip.getEquipCode());
                equip.setEquipSource("0");
            	//判断是否需要处理辅助类设备关联
            	if(StringUtils.isNoneBlank(equip.getAidEquipCodes())) {
            		EntityWrapper<TtEqEquipmentAid> dew
            			=new EntityWrapper<>();
            		//删除原绑定的辅助类设备
            		dew.eq("EQUIP_CODE", equip.getEquipCode());
            		ttEEquipmentAidDao.delete(dew);
            		
            		//添加新的辅助类设备关联
            		String[] aidEquipCodes = equip.getAidEquipCodes().split(",");
            		for(String aidEquipCode : aidEquipCodes) {
            			EntityWrapper<TtEqEquipmentAid> ew = new EntityWrapper<>();
            			ew.eq("AID_EQUIP_CODE", aidEquipCode);
            			List<TtEqEquipmentAid> aidlist = ttEEquipmentAidDao.selectList(ew);
            			if(!aidlist.isEmpty()) {
            				throw new ServiceException("第"+i+"行第6列辅助设备存在已被关联");
            			}
            			TtEqEquipmentAid aid =new TtEqEquipmentAid();
            			aid.setPkId(BaseUtil.getUUID());
            			aid.setEquipCode(equip.getEquipCode());
            			aid.setAidEquipCode(aidEquipCode);
            			ttEEquipmentAidDao.insert(aid);
            		}
            	}
                equip.setEquipCodeName(data.get(i).get(20).toString());
                equip.insert();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件出错");
        } catch (IndexOutOfBoundsException e2) {
            e2.printStackTrace();
            throw new ServiceException("表格中第"+errorRow+"存在空数据");
        } catch (ParseException e) {
			e.printStackTrace();
		}
		
	}

    private void addOperatingPersonnels(String name, String equipCode) {
        //添加操作人
        String[] operatingPersonnels = name.split(",");
        for(String operatingPersonnel : operatingPersonnels) {
            SysUser user = new SysUser();
            user.setDelFlag(CommonConstants.DEL_FLAG);
            user.setUsername(operatingPersonnel);
            SysUser sysUser = this.iSysUserDao.selectOne(user);
            if(user!=null){
                EquipUsers equipUsers = new EquipUsers();
                equipUsers.setPkId(BaseUtil.getUUID());
                equipUsers.setEquipCode(equipCode);
                equipUsers.setOperatingPersonnel(sysUser.getPkId());
                equipUsers.setDelFlag(CommonConstants.DEL_FLAG);
                equipUsers.insert();
            }
        }
    }

    private Boolean checkModelCode(String modelCode) {
        if (StringUtils.isBlank(modelCode)) {
            return false;
        }
        EntityWrapper<EquipModel> ew = new EntityWrapper<>();
        ew.eq("model_code",modelCode).eq("del_flag",CommonConstants.DEL_FLAG);
        return modelDao.selectCount(ew)>0;
    }

	private boolean checkEquipCode(String string) {
        EntityWrapper<Equipment> ew =new EntityWrapper<>();
        //验证设备编号的唯一性
        List<Equipment> equipList;
        equipList = equipDao.selectPage(new Page<Equipment>(1, 1), ew.eq("EQUIP_CODE", string).eq("del_flag", CommonConstants.DEL_FLAG));
		return equipList.isEmpty();
	}

	@Override
	public PageInfo<EquipPropertyVO> listPropertyValueAll(String pkId, Filter filter) {
		Equipment equip = equipDao.selectById(pkId);
		List<EquipPropertyVO> list = this.beforeList(IEqEquipmentDao.class,filter).listPropertyValueAll(equip.getEquipCode());
		return new PageInfo<>(list);
	}

	@Override
	public Equipment getEquipmentRegisterDetilById(String pkId) {
    	Equipment equip = equipDao.getEquipmentRegisterDetilById(pkId);
    	List<TtEqEquipmentAid> list = mergeAidEquipInfo(equip.getEquipCode());
    	List<EquipUsers> listU =mergeEquipUsers(equip.getEquipCode());
    	equip.setEquipmentAids(list);
    	equip.setEquipUsers(listU);
		return equip;
	}

	@Override
	public PageInfo<EquipPropertyVO> listPropertyValueAllByPkId(String equipCode, Filter filter) {
		List<EquipPropertyVO> list = this.beforeList(IEqEquipmentDao.class,filter).listPropertyValueAll(equipCode);
		return new PageInfo<>(list);
	}

    @Override
    public List<Equipment> listAllEquipmentByModelCode(String modelCode) {
        return equipDao.listAllEquipmentByModelCode(modelCode);
    }

    @Override
    public PageInfo<Equipment> searchEquipmentEnvByCode(Filter filter, String equipCode) {
        List<Equipment> list =
                super.beforeList(IEqEquipmentDao.class, filter).searchEquipmentEnvByCode(equipCode);

        return new PageInfo<Equipment>(list);
    }
}
